package com.example.queue;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * description:
 *          多线程按顺序调用A->B->C
 *          三个线程启动，要求如下
 *          A打印5次 B打印10次 C打印15次
 *          接着
 *          A打印5次 B打印10次 C打印15次
 *          10轮
 *              1.高内聚低耦合前提下操作资源类
 *              2.判断、干活、通知
 *              3.多线程交互中，防止虚假唤醒（判断只能用while）
 *              4.标志位
 * date: 2021/3/23 13:55 <br>
 *
 * @author: ZhangYixin <br>
 * version: 1.0 <br>
 */
class ShareData{
    private int number = 1;
    Lock lock = new ReentrantLock();
    // 对应A线程执行
    Condition c1 = lock.newCondition();
    // 对应B线程执行
    Condition c2 = lock.newCondition();
    // 对应C线程执行
    Condition c3 = lock.newCondition();

    // 打印5次
    public void printC1(){
        lock.lock();
        try {
            // 1.判断
            while (number != 1){
                c1.await();
            }
            // 2.干活
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName()+"\t "+i);
            }
            // 3.通知
            number = 2;
            c2.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    // 打印10次
    public void printC2(){
        lock.lock();
        try {
            // 1.判断
            while (number != 2){
                c2.await();
            }
            // 2.干活
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName()+"\t "+i);
            }
            // 3.通知
            number = 3;
            c3.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    // 打印15次
    public void printC3(){
        lock.lock();
        try {
            // 1.判断
            while (number != 3){
                c3.await();
            }
            // 2.干活
            for (int i = 0; i < 15; i++) {
                System.out.println(Thread.currentThread().getName()+"\t "+i);
            }
            // 3.通知
            number = 1;
            c1.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}

public class ConditionDemo {

    public static void main(String[] args) {
        ShareData shareData = new ShareData();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                shareData.printC1();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                shareData.printC2();
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                shareData.printC3();
            }
        },"C").start();
    }
}
